import axios from 'axios';
import store, { type PostProps } from '../store/store';
// 配置默认url
axios.defaults.baseURL = 'http://apis.imooc.com/'
// 请求拦截器
// 判断有没有通用 Authorization =  Bearer + token
// console.log(store);
axios.interceptors.request.use(config => {

  // if (store.state.token) {
  //   if (!axios.defaults.headers.common.Authorization) {
  //     axios.defaults.headers.common.Authorization = `Bearer ${store.state.token}`
  //     console.log(`Bearer ${store.state.token}`);
  //   }
  // }
  // config.params = { ...config.params, icode: 'C127E9ABDFB2F382' }
  store.commit('SETLOADING', true)
  store.commit('SETERR', { isErr: false, message: '' })
  // get 请求，添加到 url 中
  config.params = { ...config.params, icode: '8507DA6AA55C4931' }
  // 其他请求，添加到 body 中
  // 如果是上传文件，添加到 FormData 中
  if (config.data instanceof FormData) {
    config.data.append('icode', '8507DA6AA55C4931')
  } else {
    // 普通的 body 对象，添加到 data 中
    config.data = { ...config.data, icode: '8507DA6AA55C4931' }
  }
  return config
})
// 响应拦截器
axios.interceptors.response.use(response => {
  store.commit('SETLOADING', false)
  return response
}, e => {
  store.commit('SETERR', { isErr: true, message: e.response.data.error })
  store.commit('SETLOADING', false)
  return Promise.reject(e.response.data.error)
})
export default axios
// /api/columns?currentPage={page}&pageSize={size} 获取专栏列表
export const reqGetColumns = () => axios.get('api/columns')
// /api/columns/{id} 获取专栏详细
export const reqGetColumn = (id: string) => axios.get(`api/columns/${id}`)
// /api/columns/{id}/posts?currentPage={page}&pageSize={size}  获取专栏文章
export const reqGetPosts = (id: string) => axios.get(`api/columns/${id}/posts`)
// /api/user/login 登陆 post
export const reqPostToken = (email: string, password: string) => axios.post(`/api/user/login`, { email, password })
// /api/user/current 获取用户信息 get 要带响应头 
export const reqGetUserInfo = () => axios.get('/api/user/current')
// 注册/api/users
export const reqCreateInfo = (data: { email: string, nickName: string, password: string }) => axios.post('/api/users', data)
// 上传文件 /api/upload  
export const reqPostFile = (data: FormData) => axios.post('/api/upload', data, { headers: { 'Content-type': 'multipart/form-data' } })
// 创建文章 /api/posts
export const reqCreatePosts = (data: PostProps) => axios.post('/api/posts', data)
// 获取单个文章信息 /api/posts/{id}
export const reqPosts = (id: string) => axios.get(`/api/posts/${id}`)